package com.penghaonan.appframework.utils

object CollectionUtils {

    @JvmStatic
    fun <T> isEmpty(array: Array<T>?): Boolean {
        return array == null || array.isEmpty()
    }

    @JvmStatic
    fun <T> isEmpty(collection: List<T>?): Boolean {
        return collection == null || collection.isEmpty()
    }

    @JvmStatic
    fun <T> notEmpty(collection: List<T>?): Boolean {
        return !isEmpty<T>(collection)
    }

    @JvmStatic
    fun <T> notEmpty(array: Array<T>?): Boolean {
        return !isEmpty(array)
    }

    @JvmStatic
    fun <T> size(collection: MutableCollection<T>?): Int {
        return collection?.size ?: 0
    }

    /**
     * 避免使用Collection.addAll()的时候，参数为null的问题
     */
    @JvmStatic
    fun <T> addAll(parent: MutableCollection<T>?, child: MutableCollection<T>?) {
        if (parent == null || child == null) {
            return
        }
        parent.addAll(child)
    }

    @JvmStatic
    fun <T> clearNullItem(collection: MutableCollection<T>): Int {
        val iterator = collection.iterator()
        var count = 0
        while (iterator.hasNext()) {
            if (iterator.next() == null) {
                iterator.remove()
                count++
            }
        }
        return count
    }

    @JvmStatic
    fun <T> switch(collection: MutableList<T>, from: Int, to: Int) {
        val item = collection[to]
        collection[to] = collection[from]
        collection[from] = item
    }
}

fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
    if (index1 in 0 until size && index2 in 0 until size && index1 != index2) {
        val tmp = get(index1)
        set(index1, get(index2))
        set(index2, tmp)
    }
}
